package com.lepinwenhua.roomdemo;

import java.util.List;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

/**
 * @author: 魏从响
 * @date: 2025/10/27
 * @class: FruitViewModel
 */
public class FruitViewModel extends ViewModel {
    private FruitRepository repository;
    private LiveData<List<Fruit>> allFruits;

    // 应用上下文，用于获取数据库实例
    private android.app.Application application;

    public FruitViewModel(android.app.Application application) {
        this.application = application;
        AppDatabase database = MyApplication.getDatabase(); // 通过自定义的Application获取数据库实例
        repository = new FruitRepository(database.fruitDao());
        allFruits = repository.getAllFruits();
    }

    public LiveData<List<Fruit>> getAllFruits() {
        return allFruits;
    }

    public void insert(Fruit fruit) {
        repository.insert(fruit);
    }

    public void insertAll(Fruit... fruits) {
        repository.insertAll(fruits);
    }

    public void update(Fruit fruit) {
        repository.update(fruit);
    }

    public void delete(Fruit fruit) {
        repository.delete(fruit);
    }
}

